

//增加新窗口
Scene_Title.prototype.create = function () {
    Scene_Base.prototype.create.call(this);
    this.createBackground();
    this.createForeground();
    this.createWindowLayer();
    this.createLogonWindow();
    this.createTipWindow();
}

Scene_Title.prototype.createLogonWindow = function () {
    const background = $dataSystem.titleCommandWindow.background;
    const rect = this.logonWindowRect();
    this._logonWindow = new Window_Logon(rect);
    this._logonWindow.setBackgroundType(background);
    this.addWindow(this._logonWindow);
}

Scene_Title.prototype.logonWindowRect = function () {
    const ww = 600;
    const wh = 320;
    const wx = Graphics.boxWidth / 2 - 300;
    const wy = Graphics.boxHeight / 2 - 160;
    return new Rectangle(wx, wy, ww, wh);
}

Scene_Title.prototype.createTipWindow = function () {
    const rect = this.tipWindowRect();
    this._tipWindow = new Window_Tip(rect);
    this._logonWindow.setTipWindow(this._tipWindow);
    this.addWindow(this._tipWindow);
}

Scene_Title.prototype.tipWindowRect = function () {
    const ww = Graphics.boxWidth;
    const wh = 150;
    const wx = 0;
    const wy = 100;
    return new Rectangle(wx, wy, ww, wh);
}

Scene_Title.prototype.drawGameTitle = function () {
    const x = 20;
    const y = 75;
    const maxWidth = Graphics.width - x * 2;
    const text = $dataSystem.gameTitle;
    const bitmap = this._gameTitleSprite.bitmap;
    bitmap.fontFace = $gameSystem.mainFontFace();
    bitmap.outlineColor = "black";
    bitmap.outlineWidth = 8;
    bitmap.fontSize = 72;
    bitmap.drawText(text, x, y, maxWidth, 48, "center");
}

Scene_Title.prototype.update = function () {
    if (!this.isBusy()) {
        this._logonWindow.open();
    }
    Scene_Base.prototype.update.call(this);
};

Scene_Title.prototype.isBusy = function () {
    return Scene_Base.prototype.isBusy.call(this);
}

Window_Base.prototype.pageX = function () {
    if (Graphics._canvas) {
        const left = Graphics._canvas.offsetLeft;
        const x = this.x;
        return Math.round(x * Graphics._realScale + left);
    } else {
        return 0;
    }
}

Window_Base.prototype.pageY = function () {
    if (Graphics._canvas) {
        const top = Graphics._canvas.offsetTop;
        const y = this.y;
        return Math.round(y * Graphics._realScale + top);
    } else {
        return 0;
    }
}

Window_Base.prototype.drawCharacter = function (characterName, characterIndex, x, y, width, height) {
    // const rect = this.itemLineRect(0);
    const bitmap = ImageManager.loadCharacter(characterName);
    const big = ImageManager.isBigCharacter(characterName);
    bitmap.addLoadListener(() => {
        width = width || ImageManager.faceWidth;
        height = height || ImageManager.faceHeight;
        const pw = bitmap.width / (big ? 3 : 12);
        const ph = bitmap.height / (big ? 4 : 8);
        const n = big ? 0 : characterIndex;
        const sx = ((n % 4) * 3 + 1) * pw;
        const sy = Math.floor(n / 4) * 4 * ph;
        const dx = x - pw / 2;
        const dy = y - ph - 30;
        this.contents.blt(bitmap, sx, sy, pw, ph, dx, dy);
    })
}

class Window_Logon extends Window_Base {
    initialize(rect) {
        super.initialize(rect);
        this.inputIsAdd = false;
        this._realScale = Graphics._realScale;
        this._isBusy = false;
        this.creatInput();
        this.createButton();
        this.refresh();
    }

    creatInput() {
        this._userInput = NetManager.createInput();
        this._passwordInput = NetManager.createInput();
        this.updateInput();
    }

    createButton() {
        const x1 = 50;
        const x2 = 350;
        const y = 240;
        this.createLogonButton(x1, y);
        this.createRegisterButton(x2, y);
    }

    createLogonButton(x, y) {
        const text = "登录";
        const fun = this._logon.bind(this);
        const button = new Sprite_NetButton(x, y, text, fun);
        this.addChild(button);
        this._logonButton = button;
    }

    createRegisterButton(x, y) {
        const text = "注册";
        const fun = this._register.bind(this);
        const button = new Sprite_NetButton(x, y, text, fun);
        this.addChild(button);
        this._registerButton = button;
    }

    _logon() {
        if (this._isBusy) return;
        if (!this.inputCheck()) return;
        this._isBusy = true;
        const user = this._userInput.value.replace(/,/g, '\\');
        const password = this._passwordInput.value;
        NetManager.logon(user, password).then((data) => {
            switch (data.code) {
                case 100:
                    NetManager.token = data.token;
                    this._isBusy = false;
                    this.close();
                    SceneManager.push(Scene_ActorList);
                    break;
                case 102:
                    this._tipWindow.pop("用户名不存在");
                    this._isBusy = false;
                    break;
                case 103:
                    this._tipWindow.pop("密码错误");
                    this._isBusy = false;
                    break;
                default:
                    this._tipWindow.pop("寄");
                    this._isBusy = false;
                    break;
            }
        })
    }

    _register() {
        if (this._isBusy) return;
        if (!this.inputCheck()) return;
        this._isBusy = true;
        const user = this._userInput.value.replace(/,/g, '\\');
        const password = this._passwordInput.value;
        NetManager.register(user, password).then((data) => {
            switch (data.code) {
                case 100:
                    this._tipWindow.pop("注册成功");
                    this._isBusy = false;
                    break;
                case 101:
                    this._tipWindow.pop("用户名已存在");
                    this._isBusy = false;
                    break;
                default:
                    this._tipWindow.pop("寄");
                    break;
            }
        })
    }

    inputCheck() {
        const user = this._userInput.value;
        const password = this._passwordInput.value;
        if (user === "" || password === "") {
            this._tipWindow.pop("用户名或密码不能为空！");
            return false;
        } else if (password.length < 6) {
            this._tipWindow.pop("密码不能小于6位！");
            return false;
        }
        return true;
    }

    refresh() {
        this.drawTitle();
        this.drawItem();
    }

    drawTitle() {
        const x = 0;
        const y = 30;
        const w = 580;
        const text = "登录";
        this.contents.fontSize = 68;
        this.drawText(text, x, y, w, "center");
        this.contents.fontSize = 26;
    }

    drawItem() {
        const x = 60;
        const y1 = 110;
        const y2 = 170;
        const w = 500;
        const text1 = "账号:";
        const text2 = "密码:";
        this.contents.fontSize = 35;
        this.drawText(text1, x, y1, w, "left");
        this.drawText(text2, x, y2, w, "left");
    }

    open() {
        super.open();
        if (this._userInput && !this.inputIsAdd) {
            document.body.appendChild(this._userInput);
            document.body.appendChild(this._passwordInput);
            this.inputIsAdd = true;
        }
    }

    close() {
        super.close();
        if (this._userInput) {
            this._userInput.remove();
            this._passwordInput.remove();
        }
    }

    update() {
        super.update();
        if (this._realScale != Graphics._realScale && this._userInput) {
            this.updateInput();
        }
    }

    //画面缩放后保证input元素位置不变
    updateInput() {
        const x = this.pageX() + 170 * Graphics._realScale;
        const y1 = this.pageY() + 125 * Graphics._realScale;
        const y2 = this.pageY() + 185 * Graphics._realScale;
        const w = 350 * Graphics._realScale;
        const h = 35 * Graphics._realScale;
        this._userInput.style.left = `${x}px`;
        this._passwordInput.style.left = `${x}px`;
        this._userInput.style.top = `${y1}px`;
        this._passwordInput.style.top = `${y2}px`;
        this._userInput.style.width = `${w}px`;
        this._passwordInput.style.width = `${w}px`;
        this._userInput.style.height = `${h}px`;
        this._passwordInput.style.height = `${h}px`;
        this._realScale = Graphics._realScale;
    }

    setTipWindow(tipWindow) {
        this._tipWindow = tipWindow;
    }
}

class Scene_ActorList extends Scene_Base {
    initialize() {
        super.initialize();
        Scene_Title.prototype.createBackground.call(this);
        this.createWindowLayer();
        this.createAllWindow();
        this.adjustBackground();
        this.creatrButton();
        this.requestActorList();
    }

    createAllWindow() {
        this.createActorWindow();
        this.createHelpWindow();
        this.createNewActorWindow();
        this.createTipWindow();
    }

    createActorWindow() {
        const rect = this.actorWindowRect();
        this._actorWindow = new Window_ActorList(rect);
        this._actorWindow.setHandler("ok", this._onOk.bind(this));
        this.addWindow(this._actorWindow);
    }

    actorWindowRect() {
        const ww = Graphics.boxWidth;
        const wh = 600;
        const wx = 0;
        const wy = Graphics.boxHeight - wh;
        return new Rectangle(wx, wy, ww, wh);
    }

    createHelpWindow() {
        const rect = this.helpWindowRect();
        this._helpWindow = new Window_Help(rect);
        this.addWindow(this._helpWindow);
        const text = "欢迎来到神的虚无主义，希望你玩的开心！"
        this._helpWindow.setText(text);
    }

    helpWindowRect() {
        const wx = 0;
        const wy = 0;
        const ww = Graphics.boxWidth;
        const wh = 120;
        return new Rectangle(wx, wy, ww, wh);
    }

    createNewActorWindow() {
        const rect = this.newActorWindowRect();
        this._newActorWindow = new Window_CreateActor(rect);
        this.addWindow(this._newActorWindow);
        this._newActorWindow.hide();
        this._newActorWindow.setHelpWindow(this._helpWindow);
        this._newActorWindow.setActorWindow(this._actorWindow);
    }

    newActorWindowRect() {
        const ww = Graphics.boxWidth / 3;
        const wh = Graphics.boxHeight;
        const wx = (Graphics.boxWidth - ww) / 2;
        const wy = 0;
        return new Rectangle(wx, wy, ww, wh);
    }

    createTipWindow() {
        const rect = this.tipWindowRect();
        this._tipWindow = new Window_Tip(rect);
        this.addWindow(this._tipWindow);
        this._newActorWindow.setTipWindow(this._tipWindow);
    }

    tipWindowRect() {
        const ww = Graphics.boxWidth;
        const wh = 150;
        const wx = 0;
        const wy = 50;
        return new Rectangle(wx, wy, ww, wh);
    }

    adjustBackground() {
        this.scaleSprite(this._backSprite1);
        this.scaleSprite(this._backSprite2);
        this.centerSprite(this._backSprite1);
        this.centerSprite(this._backSprite2);
    }

    creatrButton() {
        const x1 = Graphics.boxWidth - 120;
        const x2 = 450;
        const y = Graphics.boxHeight - 60;
        //this.createStartButton(x1, y);
        // this.createRegisterButton(x2, y);
    }

    createStartButton(x, y) {
        const text = "进入游戏";
        const fun = this._start.bind(this);
        const button = new Sprite_NetButton(x, y, text, fun);
        this.addChild(button);
        this._registerButton = button;
    }

    requestActorList() {
        NetManager.getActorList().then((data) => {
            switch (data.code) {
                case 100:
                    this._actorWindow._data = data.actor;
                    //添加null作为创建角色用
                    this._actorWindow._data.push(null);
                    this._actorWindow.refresh();
                    this._actorWindow.activate();
                    break;
                default:
                    this._tipWindow.pop("寄");
                    break;
            }
        })
    }

    _onOk() {
        const index = this._actorWindow.index();
        const actorData = this._actorWindow.itemAt(index);
        if (!actorData) {
            this.createActor();
            return;
        } else {
            //进入游戏
            const { uid } = actorData;
            NetManager.startGame(uid);
        }
    }

    createActor() {
        this._helpWindow.hide();
        this._actorWindow.hide();
        this._actorWindow.deactivate();
        this._newActorWindow.show();
        document.body.appendChild(this._newActorWindow._nameInput);
    }
}

class Window_ActorList extends Window_Selectable {
    initialize(rect) {
        super.initialize(rect);
        this._data = [];
    }

    maxCols() {
        return 3;
    }

    itemHeight() {
        return this.height / 2 - 16;
    }

    maxItems() {
        return this._data ? this._data.length : 1;
    }

    itemAt(index) {
        return this._data && index >= 0 ? this._data[index] : null;
    }

    refresh() {
        //this.makeItemList();
        Window_Selectable.prototype.refresh.call(this);
    }

    drawItem(index) {
        const actorData = this.itemAt(index);
        const rect = this.itemLineRect(index);
        if (actorData) {
            const x1 = rect.x + rect.width / 2;
            const x2 = rect.x + 10;
            const y = rect.y + 70;
            const w = rect.width - 20;
            const { name, level, class_id, character_name, character_index } = actorData;
            const className = $dataClasses[class_id].name
            const text = `lv${level} ${className}`
            this.drawCharacter(character_name, character_index, x1, y);
            this.drawText(text, x2, y, w, "center");
            this.drawText(name, x2, y + 30, w, "center");
        } else {
            const x = rect.x + 10;
            const y = rect.y + rect.height / 2;
            const w = rect.width - 20;
            const text = `创建角色`;
            this.drawText(text, x, y, w, "center");
        }
    }

    //绘制
    drawCharacter(characterName, characterIndex, x, y) {
        const rect = this.itemLineRect(0);
        const bitmap = ImageManager.loadCharacter(characterName);
        const big = ImageManager.isBigCharacter(characterName);
        bitmap.addLoadListener(() => {
            const pw = bitmap.width / (big ? 3 : 12);
            const ph = bitmap.height / (big ? 4 : 8);
            const n = big ? 0 : characterIndex;
            const sx = ((n % 4) * 3 + 1) * pw;
            const sy = Math.floor(n / 4) * 4 * ph;
            const dx = x - pw / 2;
            const dy = y - ph - 30;
            this.contents.blt(bitmap, sx, sy, pw, ph, dx, dy);
        })
    }
}

class Window_CreateActor extends Window_Base {
    initialize(rect) {
        super.initialize(rect);
        this._isBusy = false;
        this._classIndex = 0;
        this._realScale = Graphics._realScale;
        this.createButton();
        this.creatInput();
        this.createActorPool();
        this.refresh();
    }

    createButton() {
        this.createLrButton();
        this.createNewActorButton();
        this.createBackButton();
    }

    createLrButton() {
        const windowWidth = this.width;
        const x1 = 50;
        const x2 = windowWidth - 108;
        const y = 500;
        this._leftButton = new Sprite_Button("pageup");
        this._rightButton = new Sprite_Button("pagedown");
        this._leftButton.setClickHandler(this.last.bind(this));
        this._rightButton.setClickHandler(this.next.bind(this));
        this._leftButton.move(x1, y);
        this._rightButton.move(x2, y);
        this.addChild(this._leftButton);
        this.addChild(this._rightButton);
    }

    createNewActorButton() {
        const x = (this.width - 200) / 2;
        const y = this.height - 85;
        const text = "创建角色";
        const fun = this.newActor.bind(this);
        const button = new Sprite_NetButton(x, y, text, fun);
        this.addChild(button);
        this._registerButton = button;
    }

    createBackButton() {

    }

    last() {
        if (this._classIndex === 0) {
            this._classIndex = this._actorPool.length - 1;
        } else {
            this._classIndex--
        }
        this.refresh();
    }

    next() {
        const num = this._actorPool.length - 1;
        if (this._classIndex >= num) {
            this._classIndex = 0;
        } else {
            this._classIndex++
        }
        this.refresh();
    }

    newActor() {
        if (this._isBusy) return;
        if (!this.inputCheck()) return;
        this._isBusy = true;
        const name = this._nameInput.value;
        const index = this._classIndex;
        const id = this._actorPool[index].id;
        NetManager.createActor(name, id).then((data) => {
            switch (data.code) {
                case 100:
                    this._tipWindow.pop("创建成功，1s后返回");
                    this._isBusy = false;
                    setTimeout(() => {
                        this.backActorList();
                    }, 1000)
                    break;
                case 104:
                    this._tipWindow.pop("角色名已存在！");
                    this._isBusy = false;
                    break;
                default:
                    this._tipWindow.pop("寄");
                    break;
            }
        })
    }

    inputCheck() {
        const name = this._nameInput.value;
        if (name === "") {
            this._tipWindow.pop("角色名不能为空！");
            return false;
        }
        if (name.length > 8) {
            this._tipWindow.pop("角色名最多8个字！");
            return false;
        }
        return true;
    }

    backActorList() {
        this._helpWindow.show();
        this._actorWindow.show();
        this._actorWindow.activate();
        SceneManager._scene.requestActorList();
        this.hide();
        this._nameInput.remove();
    }

    creatInput() {
        this._nameInput = NetManager.createInput();
        this.updateInput();
    }

    update() {
        super.update();
        if (this._realScale != Graphics._realScale) {
            this.updateInput();
        }
    }

    //画面缩放后保证input元素位置不变
    updateInput() {
        const x = this.pageX() + 115 * Graphics._realScale;
        const y = this.pageY() + 98 * Graphics._realScale;
        const w = this.width / 2 * Graphics._realScale;
        const h = 35 * Graphics._realScale;
        this._nameInput.style.left = `${x}px`;
        this._nameInput.style.top = `${y}px`;
        this._nameInput.style.width = `${w}px`;
        this._nameInput.style.height = `${h}px`;
        this._realScale = Graphics._realScale;
    }

    createActorPool() {
        this._actorPool = $dataClassPool;
    }

    refresh() {
        const x = this.width / 2 - 10;
        const y = x + 100;
        const characterName = this._actorPool[this._classIndex].characterName;
        const characterIndex = this._actorPool[this._classIndex].characterIndex;
        this.contents.clear();
        this.darwTitle();
        this.darwClassName();
        this.darwName();
        this.drawPotentialInfo(x, y);
        this.drawCharacter(characterName, characterIndex, x, y + 48);
    }

    darwTitle() {
        const x = 0;
        const y = 16;
        const w = this.width - this.itemPadding() * 2;
        const text = "创建角色";
        this.contents.fontSize = 55;
        this.drawText(text, x, y, w, "center");
        this.contents.fontSize = 26;
    }

    darwClassName() {
        const x = 100;
        const y = 488;
        const w = this.width - 232;
        const h = 48;
        const text = this._actorPool[this._classIndex].className;
        this.contents.fillRect(x, y, w, h, "#E5E5E5");
        this.contents.fontSize = 40;
        this.drawText(text, x, y + 5, w, "center");
        this.contents.fontSize = 26;
    }

    darwName() {
        const x = 30;
        const y = 80;
        const w = this.width - 60;
        this.drawText("名字:", x, y + 5, w, "left");
    }

    drawPotentialInfo(x, y) {
        const r = this.width / 2 - 80;
        const Arr = this.actorPotentialArr();
        this.contents.drawRadarChart(x, y, r, Arr, "#FFFFFF", 1, "#D8BFD8", "#FF0000")
    }

    actorPotentialArr() {
        const index = this._classIndex + 1;
        // const param = $dataActors[index]?.meta?.Potential ?? "50, 50, 50, 50, 50, 50";
        const potential = this._actorPool[this._classIndex].potential//param.split(',').map(Number);
        const atk = Math.min(potential[1], 100);
        const mat = Math.min(potential[3], 100);
        const def = Math.min(potential[2], 100);
        const mdf = Math.min(potential[4], 100);
        const mhp = Math.min(potential[0], 100);
        const agi = Math.min(potential[5], 100);
        const Arr = [
            {
                "cur": mhp,
                "name": "体质",
                "max": 110
            },
            {
                "cur": mat,
                "name": "魔攻",
                "max": 110
            },
            {
                "cur": mdf,
                "name": "魔防",
                "max": 110
            },
            {
                "cur": agi,
                "name": "速度",
                "max": 110
            },
            {
                "cur": def,
                "name": "物防",
                "max": 110
            },
            {
                "cur": atk,
                "name": "攻击",
                "max": 110
            }
        ];
        return Arr;
    }

    setHelpWindow(helpWindow) {
        this._helpWindow = helpWindow;
    }

    setActorWindow(actorWindow) {
        this._actorWindow = actorWindow;
    }

    setTipWindow(tipWindow) {
        this._tipWindow = tipWindow;
    }
}